﻿import { Component } from '@angular/core';
import { HubConnection } from '@aspnet/signalr-client'
@Component({
    selector: 'chat',
    templateUrl: './chat.component.html'
})
export class ChatComponent {
    public currentCount = 0;
    public message: string;
    private hubConnection: HubConnection;
    private isConnected: boolean = false;
    public messages: Array<{ message: string, id: string }> = [];
    constructor() {
        this.messages = new Array<{ message: string, id: string }>();
        this.enter();
    }

    public incrementCounter() {
        this.currentCount++;
    }

    public sendMessage() {

        if (this.isConnected == false) {
            console.log('没有链接')
            return;
        }
        if (!this.message) {
            console.log('请输入内容');
            return;
        }
        this.hubConnection.invoke('send', this.message)

    }

    public sendMessageObject() {

        if (this.isConnected == false) {
            console.log('没有链接')
            return;
        }
        if (!this.message) {
            console.log('请输入内容');
            return;
        }
        this.hubConnection.invoke('sendObject', { content: this.message });

    }

    private connected(id: string) {
        console.log(`${id}进入聊天室`)
        this.messages.push({ id: id, message: '进入聊天室' });
    }
    private disconnected(id: string) {
        console.log(`${id}退出聊天室`)
        this.messages.push({ id: id, message: '退出聊天室' });
    }
    private send(id: string, message: string) {
        this.messages.push({ id: id, message: message });
        console.log('send', id, message);
    }
    private sendObject(message: { id: string, content: string }) {
        this.messages.push({
            id: message.id, message: `【消息对象】${message.content}`
        });
        console.log('sendObject', message.id, message.content);
    }

    public exit() {
        this.hubConnection.stop();
        this.isConnected = false;
    }
    public enter() {
        this.hubConnection = new HubConnection('/chat');
        this.hubConnection.on('Connected', (id) => this.connected(id));
        this.hubConnection.on('Disconnected', (id) => this.disconnected(id));
        this.hubConnection.on('Send', (id, message) => this.send(id, message));
        this.hubConnection.on('SendObject', (message) => this.sendObject(message));
        this.hubConnection.onClosed = () => {
            console.log('closed')
        }
        this.hubConnection.start()
            .then(() => this.isConnected = true);
    }
}
